package com.alliky.core.config

import android.app.Activity
import android.os.Handler

import okhttp3.Interceptor
import java.util.*

/**
 * Author wxianing
 * date 2018/6/26
 */
class Configurator private constructor() {

    companion object {
        val configs = HashMap<Any, Any>()
        private val HANDLER = Handler()
        private val INTERCEPTORS = ArrayList<Interceptor>()
        val instance = Holder.instance
    }

    init {
        configs[ConfigKeys.CONFIG_READY] = false
        configs[ConfigKeys.HANDLER] = HANDLER
    }

    private object Holder {
        val instance = Configurator()
    }

    fun configure() {

//        Logger.init(true)

        configs[ConfigKeys.CONFIG_READY] = true
//        Utils.init(AppConfig.getApplicationContext())
    }

    fun withInterceptor(interceptor: Interceptor): Configurator {
        INTERCEPTORS.add(interceptor)
        configs[ConfigKeys.INTERCEPTOR] = INTERCEPTORS
        return this
    }

    fun withApiHost(host: String): Configurator {
        configs[ConfigKeys.API_HOST] = host
        return this
    }

    fun withLoaderDelayed(delayed: Long): Configurator {
        configs[ConfigKeys.LOADER_DELAYED] = delayed
        return this
    }

    fun withWeChatAppId(appId: String): Configurator {
        configs[ConfigKeys.WECHAT_APP_ID] = appId
        return this
    }

    fun withWeChatAppSecret(appSecret: String): Configurator {
        configs[ConfigKeys.WECHAT_APP_SECRET] = appSecret
        return this
    }

    fun withActivity(activity: Activity): Configurator {
        configs[ConfigKeys.ACTIVITY] = activity
        return this
    }

    fun withJavascriptInterface(name: String): Configurator {
        configs[ConfigKeys.JAVASCRIPT_INTERFACE] = name
        return this
    }

    private fun checkConfiguration() {
        val isReady = configs[ConfigKeys.CONFIG_READY] as Boolean
        if (!isReady) {
            throw RuntimeException("Configuration is not ready,call configure")
        }
    }

    fun <T> getConfiguration(key: Any): T? {
        checkConfiguration()
        val value = configs[key]
            ?: throw NullPointerException("$key IS NULL")
        return configs[key] as T?
    }
}